package iterables;
import java.util.Iterator;

public class IterablesOrdenados<T extends Comparable<? super T>> implements Iterable <T>{
	private Iterable<T> ite1;
	private Iterable<T> ite2;


	public IterablesOrdenados(Iterable<T> it1, Iterable<T> it2) {
		this.ite1 = it1;
		this.ite2 = it2;
	}


	public Iterator<T> iterator(){
		return new IteradorOrdenados(ite1,ite2);
	}
	private class IteradorOrdenados implements Iterator<T>{

		private Iterator<T> it1;
		private Iterator<T> it2;
		private T st1;
		private T st2;
		private T s= null;
		public IteradorOrdenados(Iterable<T> ite1, Iterable<T> ite2){

			it1=ite1.iterator();
			it2=ite2.iterator();
			if(it1.hasNext()&& it2.hasNext()){
				st1 = it1.next();
				st2 = it2.next();
			}else if(it1.hasNext()&& !it2.hasNext()){
				st1 = it1.next();
			}else if(it2.hasNext()&& !it1.hasNext()){
				st2 = it2.next();
			}
		}

		public boolean hasNext() {
			return  st1 !=null || st2 != null;
		}

		public T next() {
			if(it1.hasNext()&& it2.hasNext()){
				if(st1.compareTo(st2)<=0){ 
					s = st1;
					st1 = it1.next();
				}else{
					s = st2;
					st2 = it2.next();
				}
			}else if(it1.hasNext()&& !it2.hasNext()){
				if(st2 != null && st2.compareTo(st1)<=0){
					s=st2;
					st2 = null;
				}else {
					s = st1;
					st1 = it1.next();
				}
			}else if(it2.hasNext()&& !it1.hasNext()){
				if(st1 != null && st1.compareTo(st2)<=0){
					s=st1;
					st1 = null;
				}else {
					s = st2;
					st2 = it2.next();
				}
			}else if(!it2.hasNext()&& !it1.hasNext()){
				if (st1 != null && st2 != null){
					if(st1.compareTo(st2)<=0){
						s=st1;
						st1 = null;
					}else {
						s = st2;
						st2 = null;
					}
				}else if(st1 != null){
					s=st1;
					st1 = null;
				}else{
					s=st2;
					st2 = null;

				}
			}
			return s;
		}
		public void remove() {		
		}	
	}	
}
